<?php
/**
 * @author    Medard <pingguoli@gmail.com>
 * @date      2019/3/4 15:04
 * @copyright Copyright 2018 - 2019
 *  
 *  
 * @version   1.0
 */

namespace App\Http\Middleware;

use App\Models\Official;
use App\Models\UserMenu;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;

/**
 * 后台登录验证和访问权限验证
 * Class AdminAuth
 * @package App\Http\Middleware
 */
class OfficialAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = session('wechat.oauth_user.default'); // 拿到授权用户资料
        $official = Official::where('openid', $user->getId())->first();

        if (empty($official)){
            return redirect()->route('wechat.login');
        } else {
            $currentUser = $official->user;
            /* 未开启账号退出 */
            if (empty($currentUser->status)) {
                $official->delete();
                return redirect()->route('wechat.login');
            }
            /*已登录后权限验证以及全局菜单*/


            $action = Route::currentRouteAction();
            $menuName = getAbility($action);

            /* 当前菜单 */
            $currentMenu = UserMenu::where('name', $menuName)->first();
            view()->share('currentMenu', $currentMenu);

            /* 面包屑 */
            $breadcrumb = UserMenu::getBreadcrumb($currentMenu);
            view()->share('breadcrumb', $breadcrumb);

            /* 所有菜单 */
            $menusTree = UserMenu::getAuthTreeInfo($currentMenu);

            view()->share('menusTree', $menusTree);
            view()->share('currentUser', $currentUser);
        }

        return $next($request);
    }
}
